<template>
	<div v-loading="loading" class="vip-product-goods-edit app-main-content-box">
		<!-- 标题 -->
		<app-main-title title="积分商城兑换上架" />

		<!-- 表单 -->
		<el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
			<!-- 兑换图 -->
			<el-form-item label="兑换图 ：" prop="coverImage">
				<div class="cover-img">
					<el-upload
						:action="actionUrl"
						:show-file-list="false"
						:headers="uploadHeaders"
						:on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload"
						class="app-uploader-img-plus fl"
					>
						<img v-if="form.coverImage" :src="fileBaseUrl + form.coverImage" class="avatar" />
						<i v-else class="el-icon-plus app-uploader-img-plus-icon" />
					</el-upload>
					<ul class="fl upload-tips">
						<li>图片要求：</li>
						<li>1.上传的图片大小不超过1MB，仅支持JPG/PNG格式</li>
						<li>2.像素大小控制在1000像素*600像素以下</li>
						<li>3.请尽量让重点内容放在图片的中间，在某一些场景我们会截取中间一个正方形的区域显示给顾客</li>
					</ul>
				</div>
			</el-form-item>

			<!-- 兑换标题 -->
			<el-form-item label="兑换标题：" prop="title">
				<el-input v-model="form.title" placeholder="请输入兑换标题" maxlength="60" show-word-limit clearable class="input-append-400" />
			</el-form-item>

			<!-- 兑换时间 -->
			<el-form-item label="兑换时间：" prop="lineTime">
				<el-date-picker
					v-model="form.lineTime"
					:default-time="['00:00:00', '23:59:59']"
					type="datetimerange"
					range-separator="~"
					value-format="yyyy-MM-dd HH:mm"
					format="yyyy-MM-dd HH:mm"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
				/>
			</el-form-item>

			<!-- 面向对象 -->
			<el-form-item label="面向对象：" prop="limitGradeRadio" class="is-required">
				<el-radio v-model="form.limitGradeRadio" label="1">全部会员</el-radio>
				<!-- <div> -->
				<el-radio v-model="form.limitGradeRadio" label="2">自定义</el-radio>
				<el-collapse-transition>
					<el-card v-if="form.limitGradeRadio === '2'" :body-style="{ 'padding-bottom': '0px' }" class="nest-card-box">
						<el-form-item prop="limitGrade">
							<div>请勾选可参与此积分兑换的对象：</div>
							<el-checkbox-group v-model="form.limitGrade">
								<el-checkbox v-for="item in cardList" :key="item.id" :label="String(item.id)" :disabled="!item.status">
									{{ item.status ? item.categoryName : item.categoryName + '(已停用)' }}
								</el-checkbox>
							</el-checkbox-group>
						</el-form-item>
					</el-card>
				</el-collapse-transition>
				<!-- </div> -->
			</el-form-item>

			<!-- 兑换类型 -->
			<el-form-item label="兑换类型：" prop="productType" class="is-required">
				<div><el-radio v-model="form.productType" :label="0">卡券</el-radio></div>
			</el-form-item>

			<!-- 赠送优惠券 -->
			<el-form-item v-if="form.productType === 0" label="卡券：" prop="couponList">
				<el-radio-group v-model="form.couponVerRadio" @change="couponVerRadioChange">
					<el-radio label="2">兑换卡券</el-radio>
					<el-radio label="1">兑换券(已弃用)</el-radio>
				</el-radio-group>
				<div class="nest-card-box">
					<el-table :data="form.couponList" border stripe size="small" empty-text="暂未配置" style="width: 100%">
						<el-table-column prop="couponId" label="批次号" />
						<el-table-column prop="name" label="卡券名称" />
						<!-- <el-table-column prop="couponType" label="卡券类型">
             <template slot-scope="scope">
             {{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType] }}
             </template>
             </el-table-column> -->
						<el-table-column prop="amount" label="数量" width="170px">
							<template slot-scope="scope">
								<el-form-item :prop="'couponList[' + scope.$index + '].num'" :rules="rules.couponNum">
									<el-input-number v-model="scope.row.num" :min="1" :max="99" maxlength="2" label="数量" style="margin-top: 18px" />
								</el-form-item>
							</template>
						</el-table-column>
						<el-table-column label="操作" width="80">
							<template slot-scope="scope">
								<el-button type="text" @click="delCardCoupon(scope.$index)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
					<el-button
						v-if="form.couponVerRadio === '2'"
						:disabled="form.couponList.length >= 10"
						type="text"
						icon="el-icon-plus"
						style="display:block"
						@click.native.prevent="openDialogCardCouponTable"
					>
						增加卡券
					</el-button>
					<!--<el-button-->
					<!--  v-if="form.couponVerRadio==='1'"-->
					<!--  disabled="false"-->
					<!--  type="text"-->
					<!--  icon="el-icon-plus"-->
					<!--  style="display:block"-->
					<!--  @click.native.prevent="openCouponList"-->
					<!--&gt;增加券-->
					<!--</el-button>-->
					<div style="font-size: 12px;color: #606266">单次最多添加卡券种类不超过10种，卡券总数量不超过30张（因为微信限制，暂不支持配置微信商家券）</div>
				</div>
			</el-form-item>
			<!--      &lt;!&ndash; 兑换类型是优惠券 &ndash;&gt;-->
			<!--      <el-form-item label="优惠券：" prop="couponList">-->
			<!--        &lt;!&ndash; 券列表 &ndash;&gt;-->
			<!--        <ul>-->
			<!--          <li v-for="(item,index) in form.couponList" :key="index">-->
			<!--            <span class="coupon-list">{{ item.name + '（' + item.description + '）' }}</span>-->
			<!--            <el-form-item-->
			<!--              :prop="'couponList[' + index + '].num'"-->
			<!--              :rules="rules.couponMum"-->
			<!--              style="display:inline-block"-->
			<!--            >-->
			<!--              <el-input v-model="item.num" style="width:120px;vertical-align:top;" maxlength="2">-->
			<!--                <template slot="append">张</template>-->
			<!--              </el-input>&nbsp;&nbsp;-->
			<!--            </el-form-item>-->
			<!--            &lt;!&ndash; 删除按钮 &ndash;&gt;-->
			<!--            <el-button-->
			<!--              type="text"-->
			<!--              icon="el-icon-delete"-->
			<!--              style="display:inline"-->
			<!--              @click="delCoupon(index)"-->
			<!--            >删除-->
			<!--            </el-button>-->
			<!--          </li>-->
			<!--        </ul>-->
			<!--        &lt;!&ndash; 新增按钮 &ndash;&gt;-->
			<!--        <el-button-->
			<!--          :disabled="form.couponList.length>=5"-->
			<!--          type="text"-->
			<!--          icon="el-icon-plus"-->
			<!--          style="display:block"-->
			<!--          @click="openCouponList"-->
			<!--        >增加券-->
			<!--        </el-button>-->
			<!--      </el-form-item>-->

			<!-- 兑换积分 -->
			<el-form-item label="兑换积分：" prop="productPoint">
				<el-input v-model="form.productPoint" maxlength="7" class="input-append-200">
					<template slot="append">
						个
					</template>
				</el-input>
			</el-form-item>

			<!-- 市场价 -->
			<el-form-item label="市场价：" prop="marketPrice">
				<el-input v-model="form.marketPrice" class="input-append-200" @change="changeMarketPrice">
					<template slot="append">
						元
					</template>
				</el-input>
			</el-form-item>

			<!-- 兑换限制 -->
			<el-form-item label="兑换限制：" prop="userTotalLimit">
				<el-radio v-model="form.userTotalLimitRadio" label="1">不限</el-radio>
				<br />
				<el-radio v-model="form.userTotalLimitRadio" label="2">每个顾客限兑换&nbsp;&nbsp;</el-radio>
				<el-input v-model="form.userTotalLimit" :disabled="form.userTotalLimitRadio === 1" class="input-append-200" maxlength="2">
					<template slot="append">
						份
					</template>
				</el-input>
			</el-form-item>

			<!-- 兑换总量 -->
			<el-form-item v-if="type === 'add'" label="兑换总量：" class="is-required">
				<div style="margin-bottom: 18px;"><el-radio v-model="form.totalQtyRadio" label="1">不限</el-radio></div>
				<el-radio v-model="form.totalQtyRadio" label="2">兑换库存&nbsp;&nbsp;</el-radio>
				<el-form-item prop="totalQty" class="app-display-i-b">
					<el-input v-model="form.totalQty" :disabled="form.totalQtyRadio !== '2'" class="input-append-200" maxlength="7">
						<template slot="append">
							份
						</template>
					</el-input>
				</el-form-item>
				<br />
				<el-radio v-model="form.totalQtyRadio" label="3">每天更新库存为&nbsp;&nbsp;</el-radio>
				<el-form-item prop="stockDailyLimit" class="app-display-i-b">
					<el-input v-model="form.stockDailyLimit" :disabled="form.totalQtyRadio !== '3'" class="input-append-200" maxlength="7">
						<template slot="append">
							份
						</template>
					</el-input>
				</el-form-item>
			</el-form-item>

			<el-form-item v-if="type === 'edit'" label="兑换总量：" class="is-required">
				<div v-if="form.totalQtyRadio === '1'">不限</div>
				<div v-else-if="form.totalQtyRadio === '2'">
					总投放：{{ form.totalQty }}，剩余库存：
					<span class="app-text-color-danger">{{ form.remainQty }}</span>
					&nbsp;&nbsp;
					<el-button round type="primary" @click="increaseStock('totalQty')">增加库存</el-button>
					<el-button :disabled="form.remainQty === 0" round @click="reduceStock('totalQty')">减少库存</el-button>
				</div>
				<div v-else>
					每日投放：{{ form.stockDailyLimit }}，当天剩余库存：
					<span class="app-text-color-danger">{{ form.stockDailyLimit - form.todaySalesNum }}</span>
					&nbsp;&nbsp;
					<el-button round type="primary" @click="increaseStock('stockDailyLimit')">增加库存</el-button>
					<el-button :disabled="form.remainQty === 0" round @click="reduceStock('stockDailyLimit')">减少库存</el-button>
				</div>
			</el-form-item>

			<!-- 更多配置 -->
			<div class="app-main-filter-collapse-box">
				<el-collapse>
					<el-collapse-item title="其它配置" name="1">
						<!-- 詳情说明 -->
						<el-form-item label="详细说明：" prop="description">
							<el-input v-model="form.description" :autosize="{ minRows: 2, maxRows: 10 }" type="textarea" placeholder="请输入" class="input-append-600" />
						</el-form-item>
					</el-collapse-item>
				</el-collapse>
			</div>

			<!-- 按钮 -->
			<el-form-item>
				<el-button type="primary" round @click="handleSubmit('form')">保存</el-button>
				<el-button round @click="routerBack">取消</el-button>
			</el-form-item>
		</el-form>

		<!-- 图库 -->
		<card-img-map ref="cardImgMap" img-type="卡面" />
		<!-- 弹框活动券 -->
		<!-- 券1.0 筛选表格 -->
		<dialog-coupon-list ref="dialogCouponList" />
		<!--券2.0 筛选表格 -->
		<DialogCardCouponTable
			ref="dialogCardCouponTable"
			:card-coupon-type="['cash', 'discount', 'exchange', 'cash_wx_pay', 'times', 'gift']"
			:has-checked-ids="hasCheckedCardCouponIds"
		/>
	</div>
</template>

<script>
import { validateCustomPositiveInt, validatePositiveInt, validateStrLen } from '@/utils/validate.js';
import { valid2Decimal6 } from '@/utils/validator.js';
import { imgUploadUrl } from '@/api/upload';
import { getAllVipCardList } from '@/api/vip';
import { addProduct, updateProduct, getProductDetail, modifyTotalStock, modifyDailyStock } from '@/api/points';
import { mapGetters } from 'vuex';
import DialogCouponList from '@/components/DialogCouponList';
import DialogCardCouponTable from '@/components/DialogCardCouponTable';

export default {
	components: {
		DialogCouponList,
		DialogCardCouponTable
	},
	props: {
		type: {
			require: true,
			type: String
		},
		id: null
	},
	data() {
		/**
		 * 表单校验方法相关
		 */
		// 兑换标题
		const validateTitle = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请输入兑换标题'));
			} else if (!validateStrLen(value, 61)) {
				callback(new Error('长度不超过60个字符'));
			} else {
				callback();
			}
		};

		// 奖励优惠券
		const validateCouponList = (rule, value, callback) => {
			if (!value.length) {
				callback('请至少选择一种');
			} else if (value.length > 10) {
				callback('卡券种类不超过10种');
			} else {
				let maxAmount = 0;
				value.forEach(v => {
					if (validateCustomPositiveInt(v.num, 2)) {
						maxAmount += v.num;
					}
				});
				if (maxAmount > 30) {
					callback('卡券总数量不超过30张');
				} else {
					callback();
				}
			}
		};

		// 优惠券数量
		const validateCouponNum = (rule, value, callback) => {
			if (this.$isNull(value)) {
				callback('请输入数量');
			} else if (!validateCustomPositiveInt(value, 2)) {
				callback(new Error('请输入正整数'));
			} else {
				this.$refs.form.validateField(['couponList']);
				callback();
			}
		};

		// 兑换积分
		const validateProductPoint = (rule, value, callback) => {
			if (this.$isNull(value)) {
				callback(new Error('请输入兑换积分数量'));
			} else if (!validateCustomPositiveInt(value, 7)) {
				callback(new Error('请输入正整数'));
			} else {
				callback();
			}
		};

		// 市场价
		const validateMarketPrice = (rule, value, callback) => {
			if(value === ''){
				callback();
			}else if (!Number(value) || Number(value) < 0.01 || Number(value) > 999999.99) {
				callback(new Error('范围0.01~9999999.99'));
			}else{
				callback();
			}
		};

		// 兑换限制
		const validateUserTotalLimit = (rule, value, callback) => {
			if (this.form.userTotalLimitRadio === '2') {
				if (this.$isNull(value)) {
					callback(new Error('请输入每个顾客限兑换数量'));
				} else if (!validateCustomPositiveInt(value, 2)) {
					callback(new Error('请输入正整数(上限99)'));
				} else {
					callback();
				}
			} else {
				callback();
			}
		};

		// 投放总数
		const validateTotalQty = (rule, value, callback) => {
			if (this.form.totalQtyRadio === '2') {
				if (this.$isNull(value)) {
					callback(new Error('请输入投放总量'));
				} else if (!validateCustomPositiveInt(value, 7)) {
					callback(new Error('请输入正整数(上限9999999)'));
				} else {
					callback();
				}
			} else {
				callback();
			}
		};

		// 投放总数
		const validateStockDailyLimit = (rule, value, callback) => {
			if (this.form.totalQtyRadio === '3') {
				if (this.$isNull(value)) {
					callback(new Error('请输入每天更新库存量'));
				} else if (!validateCustomPositiveInt(value, 7)) {
					callback(new Error('请输入正整数(上限9999999)'));
				} else {
					callback();
				}
			} else {
				callback();
			}
		};

		// 详细说明
		const validatedescription = (rule, value, callback) => {
			if (!value) {
				callback();
			} else if (!validateStrLen(value, 512)) {
				callback(new Error('长度不超过256个汉字或512个字符'));
			} else {
				callback();
			}
		};
		return {
			/**
			 * 表单校验字段相关
			 */
			rules: {
				// 兑换图
				coverImage: [
					{
						required: true,
						message: '请上传或者选择兑换图',
						trigger: ['change']
					}
				],
				// 兑换标题
				title: [
					{
						required: true,
						validator: validateTitle,
						trigger: ['blur', 'change']
					}
				],
				// 兑换时间
				lineTime: [
					{
						required: true,
						message: '请选择兑换日期',
						trigger: ['blur', 'change']
					}
				],
				// 目标对象
				limitGrade: [
					{
						type: 'array',
						required: true,
						message: '请至少选择一个参与兑换的对象',
						trigger: ['change']
					}
				],
				// 目标对象
				couponList: [
					{
						type: 'array',
						required: true,
						validator: validateCouponList,
						trigger: ['change']
					}
				],
				// 优惠券数量
				couponNum: [
					{
						required: true,
						validator: validateCouponNum,
						trigger: ['blur', 'change']
					}
				],
				// 兑换积分
				productPoint: [
					{
						required: true,
						validator: validateProductPoint,
						trigger: ['blur', 'change']
					}
				],
				//市场价
				marketPrice: [
					{
						required: false,
						validator: validateMarketPrice,
						trigger: ['change']
					}
				],
				// 库存
				totalQty: [
					{
						required: true,
						validator: validateTotalQty,
						trigger: ['blur', 'change']
					}
				],
				// 每日更新库存
				stockDailyLimit: [
					{
						required: true,
						validator: validateStockDailyLimit,
						trigger: ['blur', 'change']
					}
				],
				// 兑换限制
				userTotalLimit: [
					{
						required: true,
						validator: validateUserTotalLimit,
						trigger: ['blur', 'change']
					}
				],
				// 详细说明
				description: [
					{
						validator: validatedescription,
						trigger: ['blur', 'change']
					}
				]
			},
			// 配置
			uploadHeaders: {}, // 上传请求头
			actionUrl: imgUploadUrl, // 上传地址
			// 状态
			loading: false,
			// 数据
			hasCheckedCardCouponIds: [], // 已选择券id
			cardList: [],
			form: {
				lineTime: [], // no params 上架时间 下架时间
				limitGradeRadio: '1', // no params 面向对象单选
				totalQtyRadio: '1', // no params 兑换总量单选
				userTotalLimitRadio: '1', // no params 用户兑换限制
				coverImage: '', // 封面图
				title: '', // 商品的标题
				onlineTime: '', // 上架时间
				offlineTime: '', // 下架时间
				limitGrade: [], // 会员级别 ""则全选or会员卡id str 1,2
				productType: 0, // 类型 0优惠券
				couponVerRadio: '2', // 卡券版本
				couponList: [], // 券list
				productPoint: null, // 需要花费的积分
				marketPrice: '', //市场价
				userTotalLimit: '', // 每个人限购买多少个 0无上限
				totalQty: '', // 总库存上限 0无上限
				stockDailyLimit: '', // 每日库存上限 0无上限
				description: '' // 详细说明
			}
		};
	},
	computed: {
		...mapGetters(['fileBaseUrl'])
	},
	watch: {
		form: {
			handler: function(val) {
				// 兑换限制
				if (val.userTotalLimitRadio === '1') {
					this.$refs.form.clearValidate(['userTotalLimit']);
				}

				// 投放总量
				if (val.totalQtyRadio === '1') {
					this.$refs.form.clearValidate(['totalQty']);
					this.$refs.form.clearValidate(['stockDailyLimit']);
				} else if (val.totalQtyRadio === '2') {
					this.$refs.form.clearValidate(['stockDailyLimit']);
				} else {
					this.$refs.form.clearValidate(['totalQty']);
				}
			},
			deep: true
		}
	},
	mounted() {
		this.initData();
	},
	methods: {
		/**
		 * 获取数据
		 */
		// 获取数据
		initData() {
			this.loading = true;
			Promise.all([this.initCardList(), this.initProductDetail()]).then(() => {
				this.loading = false;
			});
		},
		// 获取会员卡
		initCardList() {
			return new Promise((resolve, reject) => {
				getAllVipCardList().then(res => {
					this.cardList = res.data;
					resolve();
				});
			});
		},
		// 编辑获取商品数据
		initProductDetail() {
			return new Promise((resolve, reject) => {
				if (this.type === 'edit') {
					getProductDetail({ productId: this.id }).then(res => {
						this.form = this.resetData(res.data);
						resolve();
					});
				} else {
					resolve();
				}
			});
		},

		// 格式化数据
		resetData(data) {
			// 时间
			data.lineTime = [data.onlineTime, data.offlineTime];
			// 判断类型
			if (data.productType === 0) {
				if (data.couponList.length) {
					let version = 2; // 判断是v1 还是v2
					data.couponList.some((v, i) => {
						if (i === 0) {
							version = v.itemType === 0 ? 1 : 2;
							return true;
						}
					});
					data.couponVerRadio = version === 2 ? '2' : '1';
				} else {
					data.couponVerRadio = '2';
					data.couponList = [];
				}
			}
			// 面向对象
			if (data.limitGrade === '') {
				data.limitGradeRadio = '1';
				data.limitGrade = [];
			} else {
				data.limitGradeRadio = '2';
				data.limitGrade = data.limitGrade.split(',');
			}

			// 用户兑换限制
			if (data.userTotalLimit === 0) {
				data.userTotalLimitRadio = '1';
				data.userTotalLimit = '';
			} else {
				data.userTotalLimitRadio = '2';
			}

			// 兑换总量
			if (data.totalQty === 0 && data.stockDailyLimit === 0) {
				data.totalQtyRadio = '1';
				data.totalQty = '';
				data.stockDailyLimit = '';
			} else if (data.totalQty !== 0) {
				data.totalQtyRadio = '2';
				data.stockDailyLimit = '';
			} else if (data.stockDailyLimit !== 0) {
				data.totalQtyRadio = '3';
				data.totalQty = '';
			}

			// 市场价
			data.marketPrice = data.marketPrice?(data.marketPrice / 100).toFixed(2):'';
			return data;
		},

		/**
		 * 按钮组
		 */
		// 保存
		handleSubmit(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					const params = Object.assign({}, this.form);
					// 格式化数据
					// 时间
					params.onlineTime = params.lineTime[0]; // 上架时间
					params.offlineTime = params.lineTime[1]; // 下架时间
					delete params.lineTime;

					// 面向对象
					if (params.limitGradeRadio === '1') {
						params.limitGrade = '';
					} else {
						params.limitGrade = params.limitGrade.join(',');
					}
					delete params.limitGradeRadio;

					// 判断类型
					if (params.productType !== 0) {
						params.couponList = [];
					}

					// 用户兑换限制
					if (params.userTotalLimitRadio === '1') {
						params.userTotalLimit = 0;
					}
					delete params.userTotalLimitRadio;

					// 兑换总量
					switch (params.totalQtyRadio) {
						case '1':
							params.totalQty = 0; // 总库存上限 0无上限
							params.stockDailyLimit = 0; // 每日库存上限 0无上限
							break;
						case '2':
							params.stockDailyLimit = 0;
							break;
						case '3':
							params.totalQty = 0; // 总库存上限 0无上限
							break;
					}
					delete params.totalQtyRadio;

					// 市场价
					params.marketPrice = params.marketPrice?params.marketPrice * 100:'';
					// 新增
					if (this.type === 'add') {
						this.loading = true;
						addProduct(params)
							.then(res => {
								this.$notify({
									title: '成功',
									message: '新增商品成功',
									type: 'success',
									duration: 2000,
									offset: 40
								});
								this.routerBack();
							})
							.finally(() => {
								this.loading = false;
							});
					}

					// 编辑
					if (this.type === 'edit') {
						// 删除不编辑字段
						delete params.totalQty; // 总库存
						delete params.stockDailyLimit; // 每日限库存
						delete params.remainQty; // 可用库存
						updateProduct(params)
							.then(res => {
								this.$notify({
									title: '成功',
									message: '更新商品成功',
									type: 'success',
									duration: 2000,
									offset: 40
								});
								this.routerBack();
							})
							.finally(() => {
								this.loading = false;
							});
					}
				}
			});
		},

		// 取消
		routerBack() {
			this.$router.push({ name: 'VipPointsMall' });
		},

		// 新增优惠券
		// openCouponList() {
		//   this.hasCheckedCardCouponIds = []
		//   this.form.couponList.forEach(v => {
		//     this.hasCheckedCardCouponIds.push(v.couponId)
		//   })
		//   this.$refs.dialogCouponList.open(this.hasCheckedCardCouponIds, 2).then(res => {
		//     const params = Object.assign({}, res)
		//     params.name = res.couponName
		//     params.num = params.amount
		//     delete params.couponName
		//     delete params.amount
		//     this.form.couponList.push(params)
		//   })
		// },

		// 删除优惠券
		// delCoupon(index) {
		//   this.form.couponList.splice(index, 1)
		//   this.hasCheckedCardCouponIds.splice(index, 1)
		// },

		// 新增优惠券
		openCouponList() {
			this.hasCheckedCardCouponIds = [];
			this.form.couponList.forEach(v => {
				this.hasCheckedCardCouponIds.push(v.couponId);
			});
			this.$refs.dialogCouponList.open(this.hasCheckedCardCouponIds, 2).then(res => {
				this.$refs.form.clearValidate(['couponList']);
				const couponData = Object.assign({}, res);
				const params = {
					couponId: couponData.couponId,
					description: couponData.description,
					itemType: 0,
					name: couponData.couponName,
					num: couponData.amount,
					originalPrice: null,
					serial: null
				};
				this.form.couponList.push(params);
			});
		},

		//  新增优惠券 v2
		openDialogCardCouponTable() {
			this.hasCheckedCardCouponIds = [];
			this.form.couponList.forEach(v => {
				this.hasCheckedCardCouponIds.push(v.couponId);
			});
			this.$nextTick(() => {
				this.$refs.dialogCardCouponTable.open().then(res => {
					this.$refs.form.clearValidate(['couponList']);
					const couponData = Object.assign([], res);
					const params = [];
					couponData.forEach(v => {
						params.push({
							couponId: v.couponId,
							description: v.description,
							itemType: 1,
							name: v.couponName,
							num: v.amount,
							originalPrice: null,
							serial: null
						});
					});
					this.form.couponList = this.form.couponList.concat(params);
				});
			});
		},

		// 删除优惠券
		delCardCoupon(index) {
			this.$refs.form.clearValidate(['couponList[' + index + '].couponId']);
			this.form.couponList.splice(index, 1);
			if (this.form.couponList.length <= 10) {
				this.$refs.form.validateField(['couponList']);
			}
		},

		// 增加库存
		increaseStock(type) {
			// 判断是否已达上限
			if ((type === 'totalQty' && this.form.totalQty >= 9999999) || (type === 'stockDailyLimit' && this.form.stockDailyLimit >= 9999999)) {
				this.$alert('已达到上限9999999', '温馨提示', {
					confirmButtonText: '确定',
					center: true,
					type: 'warning',
					callback: action => {}
				});
			} else {
				this.$prompt(`当前库存：${type === 'totalQty' ? this.form.remainQty : this.form.stockDailyLimit - this.form.todaySalesNum}（上限9999999）`, '请输入增加库存数量', {
					confirmButtonText: '保存',
					cancelButtonText: '取消',
					inputValidator: this.validateIncreaseQty
				})
					.then(({ value }) => {
						const params = {};
						params.increaseStockValue = value;
						params.productId = this.id;
						params.reduceStockValue = 0;
						// 发送新增请求
						this.loading = true;
						if (type === 'totalQty') {
							modifyTotalStock(params)
								.then(() => {
									this.form.totalQty = +value + this.form.totalQty;
									this.form.remainQty = +value + this.form.remainQty;
									this.$notify({
										title: '成功',
										message: '增加库存成功',
										type: 'success',
										duration: 2000,
										offset: 40
									});
								})
								.finally(() => {
									this.loading = false;
								});
						} else {
							modifyDailyStock(params)
								.then(() => {
									this.form.stockDailyLimit = +value + this.form.stockDailyLimit;
									this.$notify({
										title: '成功',
										message: '增加库存成功',
										type: 'success',
										duration: 2000,
										offset: 40
									});
								})
								.finally(() => {
									this.loading = false;
								});
						}
					})
					.catch(() => {});
			}
		},

		// 校验增加的库存
		validateIncreaseQty(val) {
			if (val === '') {
				return '请输入增加的库存数量';
			} else if (!validatePositiveInt(val)) {
				return '请输入正整数';
			}
		},

		reduceStock(type) {
			this.$prompt(
				`${type === 'totalQty' ? '当前剩余库存：' + this.form.remainQty : '当天剩余库存：' + (this.form.stockDailyLimit - this.form.todaySalesNum)}`,
				'请输入减少库存数量',
				{
					confirmButtonText: '保存',
					cancelButtonText: '取消',
					inputValidator: this.validateReduceQty
				}
			)
				.then(({ value }) => {
					const params = {};
					params.increaseStockValue = 0;
					params.productId = this.id;
					params.reduceStockValue = value;
					// 发送减少请求
					this.loading = true;
					if (type === 'totalQty') {
						modifyTotalStock(params)
							.then(() => {
								this.form.totalQty = this.form.totalQty - value;
								this.form.remainQty = this.form.remainQty - value;
								this.$notify({
									title: '成功',
									message: '减少库存成功',
									type: 'success',
									duration: 2000,
									offset: 40
								});
							})
							.finally(() => {
								this.loading = false;
							});
					} else {
						modifyDailyStock(params)
							.then(() => {
								this.form.stockDailyLimit = this.form.stockDailyLimit - value;
								this.$notify({
									title: '成功',
									message: '减少库存成功',
									type: 'success',
									duration: 2000,
									offset: 40
								});
							})
							.finally(() => {
								this.loading = false;
							});
					}
				})
				.catch(() => {});
		},

		// 校验减少的库存
		validateReduceQty(val) {
			if (val === '') {
				return '请输入减少库存数量';
			} else if (!validatePositiveInt(val)) {
				return '请输入正整数';
			}
		},

		// 图片上传
		handleAvatarSuccess(res, file) {
			this.form.coverImage = res.data.path;
		},

		// 处理图片上传前
		beforeAvatarUpload(file) {
			return this.beforeUploadImg(file, this, 1000, 600, 1);
		},

		// 打开图库
		openCardImgMap() {
			this.$refs.cardImgMap.open().then(res => {
				this.form.coverImage = res;
				this.$refs.form.clearValidate(['coverImage']);
			});
		},

		// 市场价
		changeMarketPrice(e) {
			if (!Number(e)) return;
			this.form.marketPrice = Number(e).toFixed(2);
		},

		/**
		 * 状态组
		 */
		couponVerRadioChange(v) {
			this.form.couponList = [];
			this.$refs.form.clearValidate(['couponList']);
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.vip-product-goods-edit {
	/* 输入框长度 */
	.input-append-400 {
		width: 400px;
	}

	.input-append-600 {
		width: 600px;
	}

	.input-append-200 {
		width: 200px;
	}

	/* 内层嵌套卡片 */
	.nest-card-box {
		width: 80%;
		min-width: 600px;
		max-width: 1000px;

		.el-checkbox + .el-checkbox {
			margin-left: 0;
		}

		.el-checkbox {
			margin-right: 30px;
		}
	}

	/* 上传 */
	.cover-img {
		display: flex;
		align-items: center;

		.app-uploader-img-plus {
			flex: 0 0 auto;
		}
	}

	.app-uploader-img-plus {
		width: 300px;
		height: 180px;

		.app-uploader-img-plus-icon {
			font-size: 36px;
			color: #8c939d;
			width: 300px;
			height: 180px;
			line-height: 180px;
			text-align: center;
		}

		.avatar {
			width: 300px;
			height: 180px;
			display: block;
		}
	}

	.explain-uploader {
		width: 320px;

		.app-uploader-img-plus-icon {
			width: 320px;
		}

		.avatar {
			width: 320px;
		}
	}

	.upload-tips {
		margin: 10px 20px;

		li {
			margin: 5px 0;
			font-size: 14px;
			line-height: 16px;
			color: $dark-font-color;
		}
	}
}
</style>
